package com.gaoyang.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gaoyang.domain.PaiPaiGoods;
import com.gaoyang.domain.PaiPaiIndex;
import com.gaoyang.service.PaiPaiService;
import com.gaoyang.util.DateUtils;
import com.gaoyang.util.HttpUtils4Black;
import com.gaoyang.util.MailUtil;
import com.gaoyang.util.SslUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ScheduledTasks4PaiPai {

    private Logger logger = LogManager.getLogger(MinshengTask.class);

    String appid = "paipai_h5";

    @Autowired
    PaiPaiService paiPaiService;

    //选品库表结构 searchName oriPrice heartPrice 加价幅度 库存
    //产品库 nowPrice heartPrice 新旧程度 结束timestamp
    /**
     * @description 选品入库定时任务
     * @author gaoyang
     * 1.遍历选品库的关键字name列表,调用search接口。
     * 2.选出正在拍卖的产品，并进入mongodb产品库。
     * @throws Exception
     */
    @Scheduled(fixedRate = 180000)
    public void selectProducts() throws Exception{
        logger.info("选品入库定时任务");
        //获取选品库产品列表
        List<PaiPaiIndex> list = paiPaiService.getPaiPaiIndexList();
        String functionId = "pp.dbd.biz.search.query";
        //循环产品库列表，调用search接口获取产品并入库
        for (PaiPaiIndex index : list) {
            JSONObject body = new JSONObject();
            body.put("pageNo", 1);
            body.put("pageSize", 20);
            body.put("key", index.getGoodName());
            body.put("status", 2);
            body.put("sort", "endTime_asc");
            body.put("specialType", 1);
            body.put("mpSource", 1);
            body.put("sourceTag", 6);
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("functionId", functionId);
            paramMap.put("body", body.toJSONString());
            paramMap.put("t", System.currentTimeMillis() + "");
            paramMap.put("appid", appid);
            String result = HttpUtils4Black.setPaiPaiRequest(paramMap);
            JSONObject data = JSONObject.parseObject(result).getJSONObject("result").getJSONObject("data");
            int count = data.getInteger("count");
            if (count > 0) {
                JSONArray itemList = data.getJSONArray("itemList");
                for (Object obj : itemList) {
                    JSONObject item = (JSONObject) obj;
                    PaiPaiGoods paiPaiGoods = new PaiPaiGoods();
                    paiPaiGoods.setId(item.getString("id"));
                    paiPaiGoods.setProductName(item.getString("productName"));
                    paiPaiGoods.setStartTime(item.getString("startTime"));
                    paiPaiGoods.setStartTimeDate(DateUtils.timeStamp2Date(item.getString("startTime"), null));
                    paiPaiGoods.setEndTime(item.getString("endTime"));
                    paiPaiGoods.setEndTimeDate(DateUtils.timeStamp2Date(item.getString("endTime"), null));
                    paiPaiGoods.setStartPrice(item.getString("startPrice"));
                    paiPaiGoods.setMaxPrice(item.getString("maxPrice"));
                    paiPaiGoods.setCappedPrice(item.getString("cappedPrice"));
                    paiPaiGoods.setQuality(item.getString("quality"));
                    paiPaiGoods.setHeartPrice(index.getHeartPrice());
                    paiPaiGoods.setIsRemind("0");
                    paiPaiGoods.setPic("https://m.360buyimg.com/img/s200x200_" + item.getString("primaryPic"));
                    paiPaiService.savePaiPaiGoods(paiPaiGoods);
                }
            }
        }
    }

    /**
     * 竞拍
     * 1、根据产品库的产品的结束时间，小于1分钟的取出来。
     * 2、调用current_bid_info接口获取当前价格并入库。
     * 3、当最后结束前1秒时，比较产品的价格阈值，如果低于心理阈值，调用当前价格并所指定产品的加价幅度。
     * 4、调用出价接口，传递当前价格+加价幅度。
     * 5、如果竞拍成功，库存+1
     *
     * 1、定时刷新竞拍中产品结束时间小于10分钟的实时价格
     * 2、当小于一分钟时低于心理价格则发邮件通知，手动竞拍
     * @throws Exception
     */
    @Scheduled(fixedRate = 30000)
    public void pai() throws Exception{
        logger.info("定时刷新竞拍中产品结束时间小于10分钟的实时价格 发邮件任务执行");
        List<PaiPaiGoods> paiPaiGoodsList = paiPaiService.getPaiPaiGoodsList();
        String ids = "";
        for (PaiPaiGoods paiPaiGoods : paiPaiGoodsList) {
            String id = paiPaiGoods.getId();
            ids += id + ",";
        }
        if(StringUtils.isNotBlank(ids)) {
            String idStr = ids.substring(0, ids.length() - 1);
            JSONObject body = new JSONObject();
            body.put("auctionId", idStr);
            body.put("mpSource", 1);
            body.put("sourceTag", 6);
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("functionId", "paipai.auction.current_bid_info");
            paramMap.put("body", body.toJSONString());
            paramMap.put("t", System.currentTimeMillis() + "");
            paramMap.put("appid", appid);
            String currentBitResult = HttpUtils4Black.setPaiPaiRequest(paramMap);
            JSONObject dataResult = JSONObject.parseObject(currentBitResult).getJSONObject("result");
            JSONObject dataMap = dataResult.getJSONObject("data");
            String[] idArray = ids.split(",");
            StringBuffer sb = new StringBuffer();
            for (String id : idArray) {
                JSONObject bid = dataMap.getJSONObject(id);
                String currentPrice = bid.getString("currentPrice") == null ? "0" : bid.getString("currentPrice");
                long actualEndTime = bid.getLong("actualEndTime");
                paiPaiService.updatePaiPaiCurrentPrice(id, currentPrice);
                long now = System.currentTimeMillis();
                long minute = (actualEndTime - now)/(1000*60);//转化minute
                if (minute < 2){
                    PaiPaiGoods paiPaiGoods = paiPaiService.getPaiPaiGoods(id);
                    if (paiPaiGoods.getIsRemind().equals("0")) {
                        paiPaiService.updatePaiPaiIsRemind(id);
                        if (Double.parseDouble(currentPrice) < Double.parseDouble(paiPaiGoods.getHeartPrice())) {
                            sb.append("<img src='" + paiPaiGoods.getPic() + "'>" + "</br>")
                                    .append("产品名称:").append(paiPaiGoods.getProductName())
                                    .append("</br>")
                                    .append("心理价格:").append(paiPaiGoods.getHeartPrice())
                                    .append("当前价格:").append(currentPrice)
                                    .append("</br>")
                                    .append("结束时间:").append(paiPaiGoods.getEndTimeDate())
                                    .append("</br>")
                                    .append("https://paipai.m.jd.com/ppdbd/pages/detail/index?id=" + id)
                                    .append("</br>");
                        }
                    }
                    else {
                        continue;
                    }
                }
            }
            if (sb.toString().length() != 0) {
                MailUtil.sendMail("竞拍提醒", sb.toString());
                MailUtil.sendMail2("竞拍提醒", sb.toString());
            }
        }
    }

}